<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width,initial-scale=1"><title>selenium系列02-控制浏览器常用操作 | 莫伊の测试笔记</title><meta name="keywords" content="Selenium,UI自动化"><meta name="author" content="莫伊"><meta name="copyright" content="莫伊"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="访问URL访问URL可通过driver.get()方式 12# 打开百度页面driver.get(&quot;https:&#x2F;&#x2F;www.baidu.com&#x2F;&quot;) 前进、后退、刷新提供了back() forward() refresh()方法，可实现浏览器网页之间的后退和前进 123456# 页面回退driver.back()# 页面前进driver.forward()# 页面刷新drive">
<meta property="og:type" content="article">
<meta property="og:title" content="selenium系列02-控制浏览器常用操作">
<meta property="og:url" content="https://mooii.gitee.io/2021/12/14/selenium02/index.html">
<meta property="og:site_name" content="莫伊の测试笔记">
<meta property="og:description" content="访问URL访问URL可通过driver.get()方式 12# 打开百度页面driver.get(&quot;https:&#x2F;&#x2F;www.baidu.com&#x2F;&quot;) 前进、后退、刷新提供了back() forward() refresh()方法，可实现浏览器网页之间的后退和前进 123456# 页面回退driver.back()# 页面前进driver.forward()# 页面刷新drive">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://mooii.oss-cn-shanghai.aliyuncs.com/IMG_5373(20211213-233042).PNG">
<meta property="article:published_time" content="2021-12-14T15:24:14.000Z">
<meta property="article:modified_time" content="2021-12-19T14:20:39.793Z">
<meta property="article:author" content="莫伊">
<meta property="article:tag" content="Selenium">
<meta property="article:tag" content="UI自动化">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://mooii.oss-cn-shanghai.aliyuncs.com/IMG_5373(20211213-233042).PNG"><link rel="shortcut icon" href="https://mooii.oss-cn-shanghai.aliyuncs.com/%E3%83%AA%E3%82%B9%E3%81%AE%E3%82%A2%E3%82%A4%E3%82%B3%E3%83%B3%E3%81%A7%E3%81%99%E3%81%9F%E3%81%84%E3%80%82.png"><link rel="canonical" href="https://mooii.gitee.io/2021/12/14/selenium02/"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: undefined,
  translate: {"defaultEncoding":2,"translateDelay":0,"msgToTraditionalChinese":"繁","msgToSimplifiedChinese":"简"},
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '天',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    jQuery: 'https://cdn.jsdelivr.net/npm/jquery@latest/dist/jquery.min.js',
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/js/jquery.justifiedGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/css/justifiedGallery.min.css'
    },
    fancybox: {
      js: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.js',
      css: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.css'
    }
  },
  isPhotoFigcaption: true,
  islazyload: false,
  isanchor: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'selenium系列02-控制浏览器常用操作',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2021-12-19 22:20:39'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if (GLOBAL_CONFIG_SITE.isHome && /iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><link rel="stylesheet" href="/css/custom.css" media="defer" onload="this.media='all'"><!-- hexo injector head_end start --><link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/Zfour/Butterfly-swiper/swiper/swiper.min.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/Zfour/Butterfly-swiper/swiper/swiperstyle.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/Zfour/hexo-electric-clock@1.0.6/clock.css"><link rel="stylesheet" href="https://npm.elemecdn.com/hexo-butterfly-clock/lib/clock.min.css" /><link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/l-lin/font-awesome-animation/dist/font-awesome-animation.min.css" media="defer" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/hexo-butterfly-tag-plugins-plus@latest/lib/tag_plugins.min.css" media="defer" onload="this.media='all'"><script async src="https://cdn.jsdelivr.net/npm/hexo-butterfly-tag-plugins-plus@latest/lib/carousel-touch.min.js"></script><!-- hexo injector head_end end --><meta name="generator" content="Hexo 5.4.0"></head><body><div id="web_bg"></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src="https://portrait.gitee.com/uploads/avatars/user/1627/4881517_lolien_1621782146.png!avatar100" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="site-data"><div class="data-item is-center"><div class="data-item-link"><a href="/archives/"><div class="headline">文章</div><div class="length-num">35</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/tags/"><div class="headline">标签</div><div class="length-num">6</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/categories/"><div class="headline">分类</div><div class="length-num">4</div></a></div></div></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fa fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fa fa-graduation-cap"></i><span> 博文</span><i class="fas fa-chevron-down expand"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/archives/"><i class="fa-fw fa fa-folder-open"></i><span> 归档</span></a></li><li><a class="site-page child" href="/categories/"><i class="fa-fw fa fa-archive"></i><span> 分类</span></a></li><li><a class="site-page child" href="/tags/"><i class="fa-fw fa fa-tags"></i><span> 标签</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fa fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/comment/"><i class="fa-fw fa fa-paper-plane"></i><span> 留言板</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fa fa-heart"></i><span> 关于</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('https://mooii.oss-cn-shanghai.aliyuncs.com/IMG_5373(20211213-233042).PNG')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/">莫伊の测试笔记</a></span><div id="menus"><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fa fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fa fa-graduation-cap"></i><span> 博文</span><i class="fas fa-chevron-down expand"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/archives/"><i class="fa-fw fa fa-folder-open"></i><span> 归档</span></a></li><li><a class="site-page child" href="/categories/"><i class="fa-fw fa fa-archive"></i><span> 分类</span></a></li><li><a class="site-page child" href="/tags/"><i class="fa-fw fa fa-tags"></i><span> 标签</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fa fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/comment/"><i class="fa-fw fa fa-paper-plane"></i><span> 留言板</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fa fa-heart"></i><span> 关于</span></a></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">selenium系列02-控制浏览器常用操作</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2021-12-14T15:24:14.000Z" title="发表于 2021-12-14 23:24:14">2021-12-14</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2021-12-19T14:20:39.793Z" title="更新于 2021-12-19 22:20:39">2021-12-19</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/Selenium/">Selenium</a></span></div><div class="meta-secondline"></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h2 id="访问URL"><a href="#访问URL" class="headerlink" title="访问URL"></a>访问URL</h2><p>访问URL可通过<code>driver.get()</code>方式</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 打开百度页面</span></span><br><span class="line">driver.get(<span class="string">&quot;https://www.baidu.com/&quot;</span>)</span><br></pre></td></tr></table></figure>
<h2 id="前进、后退、刷新"><a href="#前进、后退、刷新" class="headerlink" title="前进、后退、刷新"></a>前进、后退、刷新</h2><p>提供了<code>back()</code> <code>forward()</code> <code>refresh()</code>方法，可实现浏览器网页之间的后退和前进</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 页面回退</span></span><br><span class="line">driver.back()</span><br><span class="line"><span class="comment"># 页面前进</span></span><br><span class="line">driver.forward()</span><br><span class="line"><span class="comment"># 页面刷新</span></span><br><span class="line">driver.refresh()</span><br></pre></td></tr></table></figure>
<h2 id="控制浏览器窗口大小"><a href="#控制浏览器窗口大小" class="headerlink" title="控制浏览器窗口大小"></a>控制浏览器窗口大小</h2><p>selenium可将浏览器设置成想要的大小、位置等</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 设置大小，参数为数字，表示窗口像素大小</span></span><br><span class="line">driver.set_window_size(<span class="number">520</span>, <span class="number">520</span>)</span><br><span class="line"><span class="comment"># 设置窗口坐标</span></span><br><span class="line">driver.set_window_position(<span class="number">30</span>,<span class="number">30</span>)</span><br><span class="line"><span class="comment"># 可同时设置窗口大小、位置等</span></span><br><span class="line">driver.set_window_rect(<span class="number">40</span>,<span class="number">80</span>,<span class="number">400</span>,<span class="number">800</span>)</span><br><span class="line"><span class="comment"># 控制浏览器窗口最大化</span></span><br><span class="line">driver.maximize_window()</span><br><span class="line"></span><br><span class="line"><span class="comment">#获取窗口大小</span></span><br><span class="line">driver.get_window_size()</span><br><span class="line"><span class="comment">#获取当前窗口坐标</span></span><br><span class="line">driver.get_window_position()</span><br><span class="line"><span class="comment"># 同时获取位置和窗口大小</span></span><br><span class="line">driver.get_window_rect()</span><br></pre></td></tr></table></figure>
<h2 id="获取页面title、url"><a href="#获取页面title、url" class="headerlink" title="获取页面title、url"></a>获取页面title、url</h2><p>有时可通过获取页面URL、title等来判断目标页面是否被正常打开，webdriver同样也提供了对应的方法</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#获取当前页面的URL</span></span><br><span class="line"><span class="built_in">print</span>(driver.current_url)</span><br><span class="line"><span class="comment">#获取当前页面的标题</span></span><br><span class="line"><span class="built_in">print</span>(driver.title)</span><br></pre></td></tr></table></figure>
<h2 id="打开、关闭标签页"><a href="#打开、关闭标签页" class="headerlink" title="打开、关闭标签页"></a>打开、关闭标签页</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 打开新的标签页</span></span><br><span class="line">js = <span class="string">&#x27;window.open(&quot;https://www.baidu.com&quot;)&#x27;</span></span><br><span class="line">driver.execute_script(js)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 通过切换句柄（后面有介绍），达到切换标签页</span></span><br><span class="line"><span class="comment"># 获取当前页面句柄</span></span><br><span class="line"><span class="built_in">print</span>(driver.current_window_handle)</span><br><span class="line"><span class="comment"># 获取浏览器所有标签页句柄</span></span><br><span class="line">windows = driver.window_handles</span><br><span class="line"><span class="built_in">print</span>(windows)</span><br><span class="line"><span class="comment"># 切换标签页</span></span><br><span class="line">driver.switch_to.window(windows[-<span class="number">1</span>])</span><br><span class="line"><span class="comment"># 关闭当前标签页</span></span><br><span class="line">driver.close()</span><br></pre></td></tr></table></figure>
<p><em>🌱 ATTENTION：</em></p>
<ul>
<li>打开新的标签页只能通过<code>js</code>来操作</li>
<li>通过切换<strong>句柄</strong>的方式可达到切换标签页的作用</li>
</ul>
<h2 id="滚动页面"><a href="#滚动页面" class="headerlink" title="滚动页面"></a>滚动页面</h2><p>由于selenium并未提供直接控制浏览器滚动的方法，所以需要通过<code>driver.execute_script()</code>来执行js，以此达到滚动浏览器的目的</p>
<h3 id="scrollBy-x-y"><a href="#scrollBy-x-y" class="headerlink" title="scrollBy(x,y)"></a>scrollBy(x,y)</h3><p>参数说明：</p>
<ul>
<li><p>X：必传，为正则向右滑动，为负则向左滑动</p>
</li>
<li><p>Y：必传，为正则向下滑动，为负则向上滑动</p>
</li>
<li><p>X、Y均为像素值</p>
</li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">driver.execute_script（<span class="string">&quot;window.scrollBy(0,1000)&quot;</span>）</span><br></pre></td></tr></table></figure>
<h3 id="scrollTo-x-y"><a href="#scrollTo-x-y" class="headerlink" title="scrollTo(x,y)"></a>scrollTo(x,y)</h3><p>参数说明：</p>
<ul>
<li>x：必传，为正则向右滑动，为负则向左滑动</li>
<li>y：必传，为正则向下滑动，为负则向上滑动</li>
<li>X、Y均为像素值</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">driver.execute_script（&quot;window.scrollTo(0,1000)&quot;）</span><br></pre></td></tr></table></figure>
<h3 id="document-documentElement-scrollTop"><a href="#document-documentElement-scrollTop" class="headerlink" title="document.documentElement.scrollTop"></a>document.documentElement.scrollTop</h3><p>获取当前滚动高度</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 获取当前滚动高度</span></span><br><span class="line">scrolTop = driver.execute_script（<span class="string">&quot;document.documentElement.scrollTop&quot;</span>）</span><br></pre></td></tr></table></figure>
<p>设置滚动高度</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 设置滚动高度</span></span><br><span class="line">driver.execute_script（<span class="string">&quot;document.documentElement.scrollTop=1000&quot;</span>）</span><br></pre></td></tr></table></figure>
<h2 id="网页frame与多窗口处理"><a href="#网页frame与多窗口处理" class="headerlink" title="网页frame与多窗口处理"></a>网页frame与多窗口处理</h2><h3 id="多窗口处理"><a href="#多窗口处理" class="headerlink" title="多窗口处理"></a>多窗口处理</h3><p>出现场景：打开链接，跳转新窗口，针对这种情况，若想在新窗口进行操作，就需要切换窗口</p>
<p>解决方案：获取窗口的唯一标识句柄标识，切换句柄就可达到切换窗口的目的</p>
<p>处理流程：</p>
<ul>
<li><code>driver.current_window_handle</code>获取当前窗口的句柄</li>
<li><code>driver.window_handles</code>获取所有的窗口句柄</li>
<li><code>driver.switch_to_window</code>跳转至对应窗口</li>
</ul>
<p>依旧以百度首页为例：点击登录-&gt;立即注册，跳转注册页面，输入用户名等</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">test_window</span>(<span class="params">self</span>):</span></span><br><span class="line">	self.driver.get(<span class="string">&quot;https://www.baidu.com/&quot;</span>)</span><br><span class="line">    self.driver.find_element_by_link_text(<span class="string">&quot;登录&quot;</span>).click()</span><br><span class="line">    <span class="comment"># 获取所有窗口列表</span></span><br><span class="line">    <span class="built_in">print</span>(self.driver.window_handles)</span><br><span class="line">    <span class="comment"># 打印当前窗口</span></span><br><span class="line">    <span class="built_in">print</span>(self.driver.current_window_handle)</span><br><span class="line">    self.driver.find_element_by_link_text(<span class="string">&quot;立即注册&quot;</span>).click()</span><br><span class="line">    <span class="comment"># 获取所有窗口列表</span></span><br><span class="line">    <span class="built_in">print</span>(self.driver.window_handles)</span><br><span class="line">    <span class="comment"># 打印当前窗口</span></span><br><span class="line">    <span class="built_in">print</span>(self.driver.current_window_handle)</span><br><span class="line">    self.driver.find_element_by_name(<span class="string">&quot;userName&quot;</span>).send_keys(<span class="string">&quot;username&quot;</span>)</span><br><span class="line">    sleep(<span class="number">5</span>)</span><br></pre></td></tr></table></figure>
<p>不切换句柄，打印的结果如下：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">[<span class="string">&#x27;CDwindow-66A675AF3A2FC4E84E31B1F02477EB7D&#x27;</span>]</span><br><span class="line">CDwindow-66A675AF3A2FC4E84E31B1F02477EB7D</span><br><span class="line">[<span class="string">&#x27;CDwindow-66A675AF3A2FC4E84E31B1F02477EB7D&#x27;</span>, <span class="string">&#x27;CDwindow-6B1868BBED3EB49AEDCD1B16275ACC15&#x27;</span>]</span><br><span class="line">CDwindow-66A675AF3A2FC4E84E31B1F02477EB7D</span><br></pre></td></tr></table></figure>
<p>从打印结果可以看出，点击立即注册之后跳转了新页面，但是当前页面依旧停留在<code>CDwindow-66A675AF3A2FC4E84E31B1F02477EB7D</code>这个页面，所以新页面的输入用户名操作是无效的</p>
<p>加上切换句柄操作后，在新页面-注册页面输入用户名成功</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">test_window</span>(<span class="params">self</span>):</span></span><br><span class="line">	self.driver.get(<span class="string">&quot;https://www.baidu.com/&quot;</span>)</span><br><span class="line">    self.driver.find_element_by_link_text(<span class="string">&quot;登录&quot;</span>).click()</span><br><span class="line">    <span class="comment"># 获取所有窗口列表</span></span><br><span class="line">    <span class="built_in">print</span>(self.driver.window_handles)</span><br><span class="line">    <span class="comment"># 打印当前窗口</span></span><br><span class="line">    <span class="built_in">print</span>(self.driver.current_window_handle)</span><br><span class="line">    self.driver.find_element_by_link_text(<span class="string">&quot;立即注册&quot;</span>).click()</span><br><span class="line">	<span class="comment"># 获取所有窗口列表</span></span><br><span class="line">    windows_all = self.driver.window_handles</span><br><span class="line">    <span class="comment"># 切换至新窗口（由于目前只有两个窗口，直接切换至列表最后一个窗口即可）</span></span><br><span class="line">    self.driver.switch_to_window(windows_all[-<span class="number">1</span>])</span><br><span class="line">    self.driver.find_element_by_name(<span class="string">&quot;userName&quot;</span>).send_keys(<span class="string">&quot;username&quot;</span>)</span><br><span class="line">    sleep(<span class="number">5</span>)</span><br></pre></td></tr></table></figure>
<p>运行结果如下：</p>
<p><img src="https://mooii.oss-cn-shanghai.aliyuncs.com/20211010121607.png" alt=""></p>
<p><em>🌱 ATTENTION：</em>对哪个页面进行操作一定要切换至对应的页面</p>
<h3 id="网页frame"><a href="#网页frame" class="headerlink" title="网页frame"></a>网页frame</h3><p>场景：web自动化中，有时定位不到网页元素，有可能这个元素存在于iframe中</p>
<p>关于frame：</p>
<ul>
<li><p>什么是frame？</p>
<ul>
<li>即HTML框架，在HTML中，框架可以在同一个浏览器中显示不止一个页面</li>
<li>基于HTML框架，可分为垂直框架和水平框架（cols、rows）</li>
</ul>
</li>
<li><p>frame分类：可分为frameset、frame、iframe</p>
<ul>
<li>frameset和普通标签一样，不影响正常定位</li>
<li>frame、iframe对selenium定位是一样的，selenium有一组方法对frame进行操作</li>
<li>frame存在两种：嵌套的和非嵌套的</li>
</ul>
</li>
</ul>
<p>切换frame方式：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 根据元素id或者index切换</span></span><br><span class="line">driver.switch_to.frame()</span><br><span class="line">driver.switch_to_frame()</span><br><span class="line"><span class="comment"># 切换到默认的frame</span></span><br><span class="line">driver.switch_to_default_content()</span><br><span class="line"><span class="comment"># 切换到父级frame</span></span><br><span class="line">driver.switch_to_parent_frame()</span><br></pre></td></tr></table></figure>
<p>处理未嵌套的frame：直接通过frame的ID或索引来切换</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">driver.switch_to.frame(<span class="string">&quot;frame的ID值&quot;</span>)</span><br><span class="line"><span class="comment"># 无ID时根据索引来处理</span></span><br><span class="line"><span class="comment"># 索引从0开始</span></span><br><span class="line">driver.switch_to.frame(<span class="string">&quot;frame的index值&quot;</span>)</span><br></pre></td></tr></table></figure>
<p>处理嵌套的frame：先切换至父节点，再切换至子节点</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">driver.switch_to.frame(<span class="string">&quot;父节点&quot;</span>)</span><br><span class="line">driver.switch_to.frame(<span class="string">&quot;子节点&quot;</span>)</span><br></pre></td></tr></table></figure>
<p><em>🌱 ATTENTION：</em>切换frame后要继续对原页面操作的话也需要切换原页面呀</p>
</article><div class="post-copyright"><div class="post-copyright__title"><span class="post-copyright-info"><h>selenium系列02-控制浏览器常用操作</h></span></div><div class="post-copyright__type"><span class="post-copyright-info"><a href="https://mooii.gitee.io/2021/12/14/selenium02/">https://mooii.gitee.io/2021/12/14/selenium02/</a></span></div><div class="post-copyright-m"><div class="post-copyright-m-info"><div class="post-copyright-a"><h>作者</h><div class="post-copyright-cc-info"><h>莫伊</h></div></div><div class="post-copyright-c"><h>发布于</h><div class="post-copyright-cc-info"><h>2021-12-14</h></div></div><div class="post-copyright-u"><h>更新于</h><div class="post-copyright-cc-info"><h>2021-12-19</h></div></div><div class="post-copyright-c"><h>许可协议</h><div class="post-copyright-cc-info"><a class="icon" rel="noopener" target="_blank" title="Creative Commons" href="https://creativecommons.org/"><i class="fab fa-creative-commons"></i></a><a rel="noopener" target="_blank" title="CC BY-NC-SA 4.0" href="https://creativecommons.org/licenses/by-nc-sa/4.0/">CC BY-NC-SA 4.0</a></div></div></div></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/Selenium/">Selenium</a><a class="post-meta__tags" href="/tags/UI%E8%87%AA%E5%8A%A8%E5%8C%96/">UI自动化</a></div><div class="post_share"><div class="social-share" data-image="https://mooii.oss-cn-shanghai.aliyuncs.com/IMG_5373(20211213-233042).PNG" data-sites="weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/social-share.js/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/social-share.js/dist/js/social-share.min.js" defer></script></div></div><div class="post-reward"><div class="reward-button button--animated"><i class="fas fa-qrcode"></i> 打赏</div><div class="reward-main"><ul class="reward-all"><li class="reward-item"><a href="https://mooii.oss-cn-shanghai.aliyuncs.com/20211021204119.png" target="_blank"><img class="post-qr-code-img" src="https://mooii.oss-cn-shanghai.aliyuncs.com/20211021204119.png" alt="微信"/></a><div class="post-qr-code-desc">微信</div></li><li class="reward-item"><a href="https://mooii.oss-cn-shanghai.aliyuncs.com/20211021204141.png" target="_blank"><img class="post-qr-code-img" src="https://mooii.oss-cn-shanghai.aliyuncs.com/20211021204141.png" alt="支付宝"/></a><div class="post-qr-code-desc">支付宝</div></li></ul></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/2021/12/15/selenium04/"><img class="prev-cover" src="https://mooii.oss-cn-shanghai.aliyuncs.com/IMG_5371(20211213-233011).PNG" onerror="onerror=null;src='/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">selenium系列04-隐式等待与显示等待</div></div></a></div><div class="next-post pull-right"><a href="/2021/12/14/selenium01/"><img class="next-cover" src="https://mooii.oss-cn-shanghai.aliyuncs.com/IMG_5372(20211213-233028).PNG" onerror="onerror=null;src='/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">selenium系列01-定位方式</div></div></a></div></nav></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src="https://portrait.gitee.com/uploads/avatars/user/1627/4881517_lolien_1621782146.png!avatar100" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">莫伊</div><div class="author-info__description">幸运交给锦鲤，你只管努力就好</div></div><div class="card-info-data"><div class="card-info-data-item is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">35</div></a></div><div class="card-info-data-item is-center"><a href="/tags/"><div class="headline">标签</div><div class="length-num">6</div></a></div><div class="card-info-data-item is-center"><a href="/categories/"><div class="headline">分类</div><div class="length-num">4</div></a></div></div><a class="button--animated" id="card-info-btn" target="_blank" rel="noopener" href="https://gitee.com/mooii"><i class="https://mooii.oss-cn-shanghai.aliyuncs.com/20211021164956.png"></i><span>我的主页</span></a></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn card-announcement-animation"></i><span>公告</span></div><div class="announcement_content">人生有限，接受事与愿违！！！</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E8%AE%BF%E9%97%AEURL"><span class="toc-number">1.</span> <span class="toc-text">访问URL</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%89%8D%E8%BF%9B%E3%80%81%E5%90%8E%E9%80%80%E3%80%81%E5%88%B7%E6%96%B0"><span class="toc-number">2.</span> <span class="toc-text">前进、后退、刷新</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%8E%A7%E5%88%B6%E6%B5%8F%E8%A7%88%E5%99%A8%E7%AA%97%E5%8F%A3%E5%A4%A7%E5%B0%8F"><span class="toc-number">3.</span> <span class="toc-text">控制浏览器窗口大小</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E8%8E%B7%E5%8F%96%E9%A1%B5%E9%9D%A2title%E3%80%81url"><span class="toc-number">4.</span> <span class="toc-text">获取页面title、url</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%89%93%E5%BC%80%E3%80%81%E5%85%B3%E9%97%AD%E6%A0%87%E7%AD%BE%E9%A1%B5"><span class="toc-number">5.</span> <span class="toc-text">打开、关闭标签页</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%BB%9A%E5%8A%A8%E9%A1%B5%E9%9D%A2"><span class="toc-number">6.</span> <span class="toc-text">滚动页面</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#scrollBy-x-y"><span class="toc-number">6.1.</span> <span class="toc-text">scrollBy(x,y)</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#scrollTo-x-y"><span class="toc-number">6.2.</span> <span class="toc-text">scrollTo(x,y)</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#document-documentElement-scrollTop"><span class="toc-number">6.3.</span> <span class="toc-text">document.documentElement.scrollTop</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%BD%91%E9%A1%B5frame%E4%B8%8E%E5%A4%9A%E7%AA%97%E5%8F%A3%E5%A4%84%E7%90%86"><span class="toc-number">7.</span> <span class="toc-text">网页frame与多窗口处理</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%A4%9A%E7%AA%97%E5%8F%A3%E5%A4%84%E7%90%86"><span class="toc-number">7.1.</span> <span class="toc-text">多窗口处理</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E7%BD%91%E9%A1%B5frame"><span class="toc-number">7.2.</span> <span class="toc-text">网页frame</span></a></li></ol></li></ol></div></div><div class="card-widget card-recommend-post"><div class="item-headline"><i class="fas fa-dharmachakra"></i><span>相关推荐</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/2021/12/14/selenium01/" title="selenium系列01-定位方式"><img src="https://mooii.oss-cn-shanghai.aliyuncs.com/IMG_5372(20211213-233028).PNG" alt="selenium系列01-定位方式"></a><div class="content"><a class="title" href="/2021/12/14/selenium01/" title="selenium系列01-定位方式">selenium系列01-定位方式</a><time datetime="2021-12-14" title="发表于 2021-12-14">2021-12-14</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2021/12/15/selenium03/" title="selenium系列03-web控件交互"><img src="https://mooii.oss-cn-shanghai.aliyuncs.com/IMG_5372(20211213-233028).PNG" alt="selenium系列03-web控件交互"></a><div class="content"><a class="title" href="/2021/12/15/selenium03/" title="selenium系列03-web控件交互">selenium系列03-web控件交互</a><time datetime="2021-12-15" title="发表于 2021-12-15">2021-12-15</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2021/12/15/selenium04/" title="selenium系列04-隐式等待与显示等待"><img src="https://mooii.oss-cn-shanghai.aliyuncs.com/IMG_5371(20211213-233011).PNG" alt="selenium系列04-隐式等待与显示等待"></a><div class="content"><a class="title" href="/2021/12/15/selenium04/" title="selenium系列04-隐式等待与显示等待">selenium系列04-隐式等待与显示等待</a><time datetime="2021-12-15" title="发表于 2021-12-15">2021-12-15</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2021/12/16/selenium05/" title="selenium系列05-js处理方式"><img src="https://mooii.oss-cn-shanghai.aliyuncs.com/IMG_5375(20211213-233124).PNG" alt="selenium系列05-js处理方式"></a><div class="content"><a class="title" href="/2021/12/16/selenium05/" title="selenium系列05-js处理方式">selenium系列05-js处理方式</a><time datetime="2021-12-16" title="发表于 2021-12-16">2021-12-16</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2021/12/16/selenium06/" title="selenium系列06-文件上传及弹框处理"><img src="https://mooii.oss-cn-shanghai.aliyuncs.com/IMG_5373(20211213-233042).PNG" alt="selenium系列06-文件上传及弹框处理"></a><div class="content"><a class="title" href="/2021/12/16/selenium06/" title="selenium系列06-文件上传及弹框处理">selenium系列06-文件上传及弹框处理</a><time datetime="2021-12-16" title="发表于 2021-12-16">2021-12-16</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2021/12/17/selenium07/" title="selenium系列07-PO处理模式"><img src="https://mooii.oss-cn-shanghai.aliyuncs.com/IMG_5375(20211213-233124).PNG" alt="selenium系列07-PO处理模式"></a><div class="content"><a class="title" href="/2021/12/17/selenium07/" title="selenium系列07-PO处理模式">selenium系列07-PO处理模式</a><time datetime="2021-12-17" title="发表于 2021-12-17">2021-12-17</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2021 - 2022 By 莫伊</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div><div class="footer_custom_text">好好学习🧡天天学习</div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="translateLink" type="button" title="简繁转换">简</button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="/js/tw_cn.js"></script><div class="js-pjax"></div><script data-pjax defer src="/js/custom/fixed_card_widget.js"></script><script id="click-heart" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/click-heart.min.js" async="async" mobile="false"></script><div id="fixedcard-dashboard"><button class="fixedcard-activebtn" type="button" title="用户信息" onclick="FixedCardWidget(&quot;class&quot;,&quot;card-info&quot;,&quot;0&quot;)"><i class="fas fa-address-book"></i></button><button class="fixedcard-activebtn" type="button" title="电子钟" onclick="FixedCardWidget(&quot;class&quot;,&quot;card-clock&quot;,&quot;0&quot;)"><i class="fas fa-cloud-sun"></i></button><button class="fixedcard-activebtn" type="button" title="相关推荐" onclick="FixedCardWidget(&quot;class&quot;,&quot;card-recommend-post&quot;,&quot;0&quot;)"><i class="fas fa-dharmachakra"></i></button><div class="fixedcard-user-avatar fixedcard-activebtn" onclick="RemoveFixedCardWidget()"><img class="fixedcard-user-avatar-img" src="https://portrait.gitee.com/uploads/avatars/user/1627/4881517_lolien_1621782146.png!avatar100" title="莫伊"></div></div></div><!-- hexo injector body_end start --> <script data-pjax>if(document.getElementById('recent-posts') && location.pathname =='/'){
    
    var parent = document.getElementById('recent-posts');
    var child = '<div class="recent-post-item" style="height: auto;width: 100%"><div class="blog-slider swiper-container-fade swiper-container-horizontal" id="swiper_container"><div class="blog-slider__wrp swiper-wrapper" style="transition-duration: 0ms"></div><div class="blog-slider__pagination swiper-pagination-clickable swiper-pagination-bullets"></div></div></div>';
    console.log('已挂载swiper')
    parent.insertAdjacentHTML("afterbegin",child)}
     </script>
<script data-pjax src="https://cdn.jsdelivr.net/gh/Zfour/Butterfly-swiper/swiper/swiper.min.js"></script>
<script data-pjax src="https://cdn.jsdelivr.net/gh/Zfour/Butterfly-swiper@0.18/swiper/swiperindex.js"></script>
<style></style><script data-pjax>function electric_clock_injector_config(){
                var parent_div_git = document.getElementsByClassName('sticky_layout')[0];
                var item_html = 'undefined';
                console.log('已挂载electric_clock')
                // parent_div_git.innerHTML=item_html+parent_div_git.innerHTML // 无报错，但不影响使用(支持pjax跳转)
                parent_div_git.insertAdjacentHTML("afterbegin",item_html) // 有报错，但不影响使用(支持pjax跳转)
            }if( document.getElementsByClassName('sticky_layout')[0] && (location.pathname ==='all'|| 'all' ==='all')){

            electric_clock_injector_config()
        } </script><script src="https://pv.sohu.com/cityjson?ie=utf-8"></script><script data-pjax  src="https://cdn.jsdelivr.net/gh/Zfour/hexo-electric-clock@1.0.6/clock.js"></script><script data-pjax>
  function butterfly_clock_injector_config(){
    var parent_div_git = document.getElementsByClassName('sticky_layout')[0];
    var item_html = '<div class="card-widget card-clock"><div class="card-glass"><div class="card-background"><div class="card-content"><div id="hexo_electric_clock"><img class="entered loading" id="card-clock-loading" src="https://npm.elemecdn.com/hexo-butterfly-clock/lib/loading.gif" style="height: 120px; width: 100%;" data-ll-status="loading"/></div></div></div></div></div>';
    console.log('已挂载butterfly_clock')
    parent_div_git.insertAdjacentHTML("afterbegin",item_html)
    }
  var elist = 'null'.split(',');
  var cpage = location.pathname;
  var epage = 'all';
  var flag = 0;

  for (var i=0;i<elist.length;i++){
    if (cpage.includes(elist[i])){
      flag++;
    }
  }

  if ((epage ==='all')&&(flag == 0)){
    butterfly_clock_injector_config();
  }
  else if (epage === cpage){
    butterfly_clock_injector_config();
  }
  </script><script src="https://pv.sohu.com/cityjson?ie=utf-8"></script><script data-pjax src="https://npm.elemecdn.com/hexo-butterfly-clock/lib/clock.min.js"></script><script async src="//at.alicdn.com/t/font_2032782_8d5kxvn09md.js"></script><!-- hexo injector body_end end --></body></html>